const config = require('../config/config.js');

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 微信登录
const wxLogin = function() {
  wx.login({
    success: res => {
      let code = res.code
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      wx.request({
        url: `${config.requestBaseUrl}/Index/getCodeInfo`,
        data: {
          code: code
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          // console.log(res.data.openid)
          if (res.data.errcode) {
            console.log(`${res.data.errcode}:${res.data.errmsg}`)
          } else {
            // console.log(`${res.data.openid}:${res.data.session_key}`)
            wx.setStorageSync('openid', res.data.openid)
            wx.setStorageSync('session_key', res.data.session_key)
          }
        },
        fail(res) {
          console.log(res)
        }
      })
    }
  })
}

// 上传文件到oss
const wxUploadFile = function(sourcePath, uploadSuccess, uploadFail) {
  let fileName = getFileName(sourcePath)
  console.log(sourcePath)
  wx.uploadFile({
    url: config.uploadUrl,
    filePath: sourcePath,
    name: 'file',
    formData: {
      key: `food/${fileName}`,
      policy: config.policy,
      OSSAccessKeyId: config.OSSAccessKeyId,
      signature: config.signature,
      success_action_status: '200',
    },
    success: function(res) {
      if (res.statusCode != 200) {
        uploadFail(res)
        return
      }
      uploadSuccess({
        fileUrl: `${config.uploadUrl}/food/${fileName}`
      })
    },
    fail: function(res) {
      uploadFail(res)
    }
  })
}

const getFileName = function(filePath) {
  let pos = filePath.lastIndexOf('/')
  let fileName = ''
  if (pos != -1) {
    fileName = filePath.substring(pos+1)
  }
  return fileName
}


const chooseImage = function (complete) {
  wx.chooseImage({
    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      complete(res)
    }
  })
}

const getUserLocation = function (callback) {
  wx.getSetting({
    success: function (res) {
      if (!res.authSetting["scope.userLocation"]) {
        wx.showModal({
          title: '请求授权位置信息',
          content: '需要您授权获取位置信息，否则无法为您提供正常服务',
          success: res => {
            console.log(res)
            if (res.cancel) {
              console.log('用户没有授权')
            } else if (res.confirm) {
              console.log("用户授权了")
              wx.openSetting({
                success: res => {
                  if (res.authSetting["scope.userLocation"]) {
                    // callback()
                  } else {
                    console.log("授权失败")
                  }
                }
              })
              callback()
            }
          }
        })
      }
    }
  })
}

const getACode = function(data) {
  return new Promise(resolve => {
    wx.request({
      url: `${config.requestBaseUrl}/Index/getACode`,
      method: 'GET',
      data: data,
      responseType: 'arraybuffer',
      success: function(res) {
        let base64 = wx.arrayBufferToBase64(res.data)
        console.log(base64)
        resolve('data:image/jpg;base64,' + base64)
      }      
    })
  })
}

const downloadACode = function(data) {
  return new Promise(resolve => {
    wx.downloadFile({
      url: `${config.requestBaseUrl}/Index/getACode?page=${data.page}&scene=${data.scene}`,
      // data: data,
      success: function (res) {
        // console.log(res)
        resolve(res.tempFilePath)
      }
    })
  })
}


module.exports = {
  formatTime: formatTime,
  wxLogin: wxLogin,
  wxUploadFile: wxUploadFile,
  chooseImage: chooseImage,
  getUserLocation: getUserLocation,
  // getAccessToken: getAccessToken,
  getACode: getACode,
  downloadACode: downloadACode
}
